package spark_core.operate_transform.keyvalue;

import java.util.Arrays;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaSparkContext;
import scala.Tuple2;


/**
 * @author shihb
 * @date 2020/1/8 11:43
 * 根据key进行排序
 */
public class SortByKeyDemo {

  public static void main(String[] args) {
    //local模式,创建SparkConf对象设定spark的部署环境
    SparkConf sparkConf = new SparkConf().setMaster("local[*]").setAppName("mark rdd");
    //创建spark上下文对象（这边是java上下文）
    JavaSparkContext sc = new JavaSparkContext(sparkConf);

    //key-value的方法要pairRdd才能调用,所以创建JavaPairRDD
    JavaPairRDD<Integer,String> inputPairRDD = sc.parallelizePairs(Arrays
        .asList(new Tuple2<>(3,"c"), new Tuple2(4, "d"), new Tuple2(1,"a"),new Tuple2(2,"b")),2);

    //升序
    JavaPairRDD<Integer,String> sortRdd = inputPairRDD.sortByKey(true,1);
    sortRdd.glom().collect().forEach(System.out::println);
    //降序
    JavaPairRDD<Integer,String> sortRdd1 = inputPairRDD.sortByKey(false,1);
    sortRdd1.glom().collect().forEach(System.out::println);
    //停止
    sc.stop();

  }
}
